package com.chat.websocket;

import com.chat.entry.dto.group.GroupChatMessageDTO;
import com.chat.entry.po.GroupMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.util.List;


@Slf4j
@Component
@RequiredArgsConstructor
public class GroupChatMessageHandler implements WebSocketHandler {
    private final WebSocketSessionManager sessionManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Integer userId = getUserId(session);

        sessionManager.addSession(userId, session);
        log.info("用户Id:{} 已连接 WebSocket", userId);
    }

    @Override
    public void handleMessage(@NotNull WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        // 收到的消息 JSON -> DTO
        GroupChatMessageDTO msg = objectMapper.readValue(message.getPayload().toString(), GroupChatMessageDTO.class);
        log.info("收到群聊消息: {}", msg);
        session.sendMessage(new TextMessage("服务器收到: " + message.getPayload()));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("Chat WebSocket 错误: {}", exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        // 断开连接时移除session
        Integer userId = getUserId(session);

        sessionManager.removeSession(userId);
        log.info("用户Id:{} 已断开连接 WebSocket", userId);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    // 从url后去userId,例如/websocket/friend/1
    private Integer getUserId(WebSocketSession session) {
        String path = session.getUri().getPath();
        String userIdStr = path.substring(path.lastIndexOf("/") + 1);
        return Integer.valueOf(userIdStr);
    }

    public boolean sendMessage(List<Integer> memberIds, GroupMessage groupMessage) {
        memberIds.forEach(memberId -> {
            WebSocketSession session = sessionManager.getSession(memberId);
            if (session != null && session.isOpen()) {
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    String payload = objectMapper.writeValueAsString(groupMessage);

                    session.sendMessage(new TextMessage(payload));
                } catch (Exception e) {
                    throw new RuntimeException("WebSocket推送失败", e);
                }
            }
        });
        return true;
    }
}
